<script setup>
import { ref, onMounted } from 'vue'
import { Modal, message } from 'ant-design-vue'
import {
  getPositionOptions,
  getPositionList,
  createPosition,
  updatePosition,
  deletePosition,
  getOrganizationList,
} from '@/api/system'

const formRef = ref()
const visible = ref(false)
const editingRecord = ref(null)
const loading = ref(false)
const searchKeyword = ref('')
const formData = ref({
  code: '',
  name: '',
  category: '',
  level: '',
  organization: '',
  maxCount: 0,
  status: '启用',
})

const columns = [
  { title: '职位编码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '职位名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '职位类别', dataIndex: 'category', key: 'category', width: 120 },
  { title: '职位等级', dataIndex: 'level', key: 'level', width: 100 },
  { title: '所属三级机构', dataIndex: 'organization', key: 'organization', width: 150 },
  { title: '最大编制数', dataIndex: 'maxCount', key: 'maxCount', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref([])
// 职位选项
const positionOptions = ref([])
// 机构选项（用于显示机构名称）
const organizationOptions = ref([])

// 获取职位列表
const fetchPositionList = async () => {
  loading.value = true
  try {
    const response = await getPositionList(searchKeyword.value || undefined)

    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id,
      }))
    } else {
      dataSource.value = []
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    message.error('获取数据失败')
    dataSource.value = []
  } finally {
    loading.value = false
  }
}

// 获取职位选项
const fetchPositionOptions = async () => {
  try {
    const response = await getPositionOptions()

    if (response && response.list) {
      positionOptions.value = response.list.map((item) => ({
        value: item.value,
        label: item.label,
        organizationId: item.organizationId,
      }))
    } else {
      positionOptions.value = []
    }
  } catch (error) {
    console.error('获取职位选项失败:', error)
    // 如果接口失败，使用空数组
    positionOptions.value = []
  }
}

// 获取机构选项（三级机构）
const fetchOrganizationOptions = async () => {
  try {
    const response = await getOrganizationList()

    if (response && response.list) {
      // 扁平化机构列表，筛选出三级机构
      const flattenOrganizations = (orgs) => {
        const result = []
        orgs.forEach((org) => {
          if (org.level === '三级机构') {
            result.push({
              id: org.id,
              code: org.code,
              name: org.name,
            })
          }
          if (org.children && org.children.length > 0) {
            result.push(...flattenOrganizations(org.children))
          }
        })
        return result
      }

      const flattenedList = flattenOrganizations(response.list)
      organizationOptions.value = flattenedList.map((org) => ({
        value: Number(org.id), // 使用数字类型的 ID
        label: org.name,
      }))
    } else {
      organizationOptions.value = []
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    organizationOptions.value = []
  }
}

// 生成职位编码（EXP + 时间戳）
const generatePositionCode = () => {
  const timestamp = Date.now()
  return `EXP${timestamp}`
}

const handleAdd = () => {
  editingRecord.value = null
  formData.value = {
    code: generatePositionCode(),
    name: '',
    category: '',
    level: '',
    organization: '',
    maxCount: 0,
    status: '启用',
  }
  visible.value = true
  // 打开弹窗时获取职位选项和机构选项
  fetchPositionOptions()
  fetchOrganizationOptions()
}

const handleEdit = (record) => {
  editingRecord.value = record
  formData.value = {
    code: record.code || '',
    name: record.name || '',
    category: record.category || '',
    level: record.level || '',
    organization: record.organizationId || record.organization || '',
    maxCount: record.maxCount || 0,
    status: record.status || '启用',
  }
  visible.value = true
  // 打开弹窗时获取机构选项
  fetchOrganizationOptions()
}

const handleDelete = async (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除职位"${record.name}"吗？`,
    async onOk() {
      try {
        await deletePosition(record.id)
        message.success('删除成功')
        fetchPositionList()
      } catch {
        message.error('删除失败，请稍后重试')
      }
    },
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    if (!editingRecord.value) {
      // 新增职位
      const organizationId = Number(formData.value.organization)
      if (!organizationId || isNaN(organizationId)) {
        message.error('请选择所属三级机构')
        return
      }

      const submitData = {
        code: formData.value.code,
        name: formData.value.name,
        category: formData.value.category,
        level: formData.value.level,
        organizationId: organizationId,
        maxCount: formData.value.maxCount,
        status: formData.value.status,
      }
      await createPosition(submitData)
      message.success('新增成功')
    } else {
      // 编辑职位
      const organizationId = Number(formData.value.organization)
      if (!organizationId || isNaN(organizationId)) {
        message.error('请选择所属三级机构')
        return
      }

      // 编辑时不需要传递code，code不可修改
      const updateData = {
        name: formData.value.name,
        category: formData.value.category,
        level: formData.value.level,
        organizationId: organizationId,
        maxCount: formData.value.maxCount,
        status: formData.value.status,
      }
      await updatePosition(editingRecord.value.id, updateData)
      message.success('编辑成功')
    }

    visible.value = false

    // 刷新列表
    fetchPositionList()
  } catch (error) {
    if (error?.errorFields) {
      return
    }
    message.error('操作失败，请稍后重试')
  }
}

const handleSearch = () => {
  fetchPositionList()
}

onMounted(() => {
  fetchPositionList()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">职位设置</h1>
      <p class="page-desc">设置职位名称以及其从属于的三级机构</p>
    </div>

    <div class="page-content">
      <div class="toolbar">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索职位名称或编码"
          style="width: 300px"
          allow-clear
          @search="handleSearch"
          @clear="handleSearch"
        />
        <a-button type="primary" @click="handleAdd">
          <template #icon>➕</template>
          新增职位
        </a-button>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="{ pageSize: 10 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)"
                >删除</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      v-model:open="visible"
      :title="editingRecord ? '编辑职位' : '新增职位'"
      width="600px"
      @ok="handleSubmit"
    >
      <a-form ref="formRef" :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item
          label="职位编码"
          name="code"
          :rules="[{ required: true, message: '请输入职位编码' }]"
        >
          <a-input
            v-model:value="formData.code"
            placeholder="系统自动生成"
            :disabled="!!editingRecord"
            readonly
            style="background-color: #f5f5f5; cursor: not-allowed"
          />
        </a-form-item>
        <a-form-item
          label="职位名称"
          name="name"
          :rules="[{ required: true, message: '请输入职位名称' }]"
        >
          <a-input v-model:value="formData.name" placeholder="请输入职位名称" />
        </a-form-item>
        <a-form-item
          label="职位类别"
          name="category"
          :rules="[{ required: true, message: '请选择职位类别' }]"
        >
          <a-select v-model:value="formData.category" placeholder="请选择职位类别">
            <a-select-option value="管理">管理</a-select-option>
            <a-select-option value="技术">技术</a-select-option>
            <a-select-option value="职能">职能</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位等级" name="level">
          <a-input v-model:value="formData.level" placeholder="请输入职位等级" />
        </a-form-item>
        <a-form-item
          label="所属三级机构"
          name="organization"
          :rules="[{ required: true, message: '请选择所属三级机构' }]"
        >
          <a-select v-model:value="formData.organization" placeholder="请选择所属三级机构">
            <a-select-option
              v-for="option in organizationOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="最大编制数" name="maxCount">
          <a-input-number
            v-model:value="formData.maxCount"
            :min="0"
            style="width: 100%"
            placeholder="请输入最大编制数"
          />
        </a-form-item>
        <a-form-item
          label="状态"
          name="status"
          :rules="[{ required: true, message: '请选择状态' }]"
        >
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="启用">启用</a-select-option>
            <a-select-option value="停用">停用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}
</style>
